<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller 
{
  function __construct()
  {
    parent::__construct();
  	$this->load->model('adminmodel');
  }
  
  function index()
  {
    $this->load->library('form_validation');
    
    $this->form_validation->set_rules('username', 'Tên truy cập', 'trim|required|xss_clean');
    $this->form_validation->set_rules('password', 'Mật khẩu', 'trim|required|xss_clean|callback_checkDatabase');
  
    if($this->form_validation->run() == FALSE) {
      $this->load->view('backend/login/index');
    } else { //if valid
      redirect('backend/category/index');
    }
  }
  
  function logout()
  {
	$_SESSION = array();
	// Remove the session ID cookie
	if (isset($_COOKIE[session_name()])) {
	  setcookie(session_name(), '', time() - 42000, '/');
	}
	session_destroy();
    redirect('backend/login/index');
  }
  
  function checkDatabase($password)
  {
    $row = $this->adminmodel->login($_POST['username'], $password);   
    if ($row) {
      $_SESSION['loggedIn'] = array(
        'id' => $row['admin_id'],
        'username' => $row['username']);
      
      return TRUE;
    } else {
      $this->form_validation->set_message('checkDatabase', 'Tên truy cập hoặc mật khẩu không chính xác');
      
      return FALSE;
    }
  }
}